package communication;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * responsible for get the data from the service - from the dirWatcher
 * and update the DB
 * 
 * @author Vladimir Sarkisyan & Erez Levy
 *
 */
public class SocketServerRunable implements Runnable{

	public SocketServerRunable(){
		
	}
	
	/**
	 * open a ServerSocket in 4444 and start to listen
	 * create ProtocolRunable2 that there is the logic 
	 * of treatment of the data that come from the service
	 * 
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	    ServerSocket serverSocket=null;
	    PrintWriter out = null;
	    BufferedReader in = null;
	    try { 
	     serverSocket = new ServerSocket(4444);
	     System.out.println("conection started 4444");
	    }
	    catch (IOException e) { 
	     System.err.println("Cannot listen on port 4444");
	     System.exit(-1);
	    }
	    Socket clientSocket=null;
	    while(true){
		    try { 
		     clientSocket=serverSocket.accept(); 
		     out=new PrintWriter(clientSocket.getOutputStream(),true);
		     in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		     // server code here...
		     //MyProtocol mp=new MyProtocol(in,out);
		     //mp.run();
		     
		     //run in different thread
		     ProtocolRunable2 pr = new ProtocolRunable2(in, out);
		     new Thread(pr).start();
		     
		     System.out.println("finish");
		     //MyProtocol2 mp2 = new MyProtocol2();
		     //mp2.run();
		    }
		    catch (IOException e) { 
		     System.err.println("Accept failed");
		     System.exit(-1);
		    }
		    finally {
		     //if (clientSocket != null) clientSocket.close(); 
		     //if (serverSocket != null) serverSocket.close();
		    }    
	    }
		
	}

	
}
